"use strict";

const Controller = require("egg").Controller;

class UserController extends Controller {
    /**
     * 添加用户
     */
    async create() {
        const { ctx } = this;
        const { username, password, nickname } = ctx.request.body;
        // 是否存在这个用户
        const user = await this.service.user.findByUsername(username);
        if (user) {
            this.ctx.body = {
                code: 404,
                message: "该用户名已注册",
            };
            return;
        }
        // 保存到数据库
        const res = await this.service.user.add({
            username,
            password,
            nickname,
        });
        // 响应
        if (res.affectedRows === 1) {
            this.ctx.body = {
                code: 201,
                message: "添加成功",
            };
        }
    }

    async index() {
        const res = await this.service.user.readListByQuery(this.ctx.query);
        this.ctx.body = {
            code: 200,
            data: res,
            message: "请求成功",
        };
    }

    async student() {
        const res = await this.service.user.getStudent();
        this.ctx.body = {
            code: 200,
            data: res,
            message: "请求成功",
        };
    }
}

module.exports = UserController;
